
local Widget = require "widgets/widget"
local Image = require "widgets/image"
local Text = require "widgets/text"
local ImageButton = require "widgets/imagebutton"
local ScrollableList = require "widgets/scrollablelist"
local TEMPLATES = require "widgets/redux/templates"

local function HandleLog()
    -- { {time1, content1}, {t2, c2}, ...}
    local log = {}
    local time
    local content = ""
    local txt =  MOD_ShroomCake and MOD_ShroomCake.ModLog
    if not txt then
        return log
    end
    for line in string.gmatch(txt, "[^\n]+") do
        if string.find(line, "^%s*(20%d%d)[%.%-%/](%d%d?)") then
            if content ~= "" then
                table.insert(log, {time, content})
                content = ""
            end
            time = line
        elseif time then
            if string.find(line, "^%-%-") then
                content = content.."------------".."\n"
            elseif (string.len (line) == 0 or string.match (line, "^%s+$")) then
            else
                content = content..line.."\n"
            end
        end
    end
    if time and content~="" then
        table.insert(log, {time, content})
    end
    return log
end
local function MakeDetailsLine(details_root, x, y, scale, image_override)
	local value_title_line = details_root:AddChild(Image("images/quagmire_recipebook.xml", image_override or "quagmire_recipe_line.tex"))
	value_title_line:SetScale(scale, scale)
	value_title_line:SetPosition(x, y)
    return value_title_line
end


local TheWindow = Class(Widget, function(self, modname)
    Widget._ctor(self, "HuxiEnterWindow")
    self.root = self:AddChild(Widget("root"))
    local backdrop = self.root:AddChild(Image("images/quagmire_recipebook.xml", "quagmire_recipe_menu_bg.tex"))
    
    local i = KnownModIndex:GetModInfo(modname)
    self.modinfo = type(i) == "table" and i or {}
    self.root:SetHAnchor(ANCHOR_MIDDLE)
    self.root:SetVAnchor(ANCHOR_MIDDLE)
    self.show_desktop = false
    local screen_w, screen_h = TheSim:GetScreenSize()
    local width = math.min(screen_w, screen_h)*1.5
    local height = width * screen_h / screen_w

    backdrop:ScaleToSize(width, height)
    


    local right_bg = backdrop:AddChild(Image("images/quagmire_recipebook.xml", "quagmire_recipe_menu_block.tex"))

    self.width_bg = width/2.3
    self.height_bg = height*0.78

    local pos_x_bg = 0.24*(width-self.width_bg)
    local top_bg = self.height_bg/2.3
    right_bg:ScaleToSize(self.width_bg, self.height_bg)
    right_bg:SetPosition(pos_x_bg, 0)


    local title = self.modinfo.name or "蘑菇慕斯 · 朝花夕拾󰀜"
    local name_font_size = 40
    self.bg_title = backdrop:AddChild(Text(HEADERFONT, name_font_size, title, UICOLOURS.BLACK))
    self.bg_title:SetPosition(pos_x_bg, top_bg)

    local top_line = top_bg - 1.2*name_font_size
    MakeDetailsLine(backdrop, pos_x_bg, top_line, -.55, "quagmire_recipe_line_break.tex"):SetScale(1, -0.5, 1)


    self.height_content = self.height_bg - top_line - 5
    self.width_content = self.width_bg - 10
    self.leftpos_content = pos_x_bg -(self.width_bg-self.width_content)/2

    self.right = self.root:AddChild(Widget("right_part"))
    self.right:SetPosition(self.leftpos_content, 0)
        
    -- left
    self.left = backdrop:AddChild(Widget("left_part"))
    self.left:SetPosition(-(width - self.width_bg)/2.5, 0)

    
    local function MakeLeftButton(title, fn, data)
        local btn1 = self.left:AddChild(ImageButton("images/global_redux.xml", "button_carny_long_normal.tex", "button_carny_long_hover.tex", "button_carny_long_disabled.tex", "button_carny_long_down.tex"))
        btn1:SetFont(CHATFONT)
        btn1.text:SetColour(0,0,0,1)
        btn1:SetTextSize(40)
        btn1:SetText(title)
        -- btn:SetScale(0.5)
        btn1:SetOnClick(function()
            self.right:KillAllChildren()
            fn(self,data)
            self.bg_title:SetString(title)
        end)
        return btn1
    end
    
    MakeLeftButton("更新日志", self.ShowLog):SetPosition(0, 120)
    MakeLeftButton("屏保模式", self.DesktopSaver):SetPosition(0, 40)
    MakeLeftButton("扫雷", self.Game):SetPosition(0, -40)
    MakeLeftButton("饥荒之旅", self.GameRecord):SetPosition(0, -120)


    self:Hide()
    self:ShowInfo()
end)

function TheWindow:ShowLog()
    local part_list = {}
    self.log = HandleLog() or {}
    for _,info in pairs(self.log)do
        local _part = Widget("txt_img_txt")
        local part_time = _part:AddChild(Text(HEADERFONT, 33, info[1], UICOLOURS.BROWN_DARK))
        local part_line = MakeDetailsLine(_part, 0, -18, .7, "quagmire_recipe_line_short.tex")
        local part_content = _part:AddChild(Text(HEADERFONT, 32, info[2], UICOLOURS.BLACK))
        
        part_content:SetRegionSize(self.width_bg*1.2, self.height_content)
        part_content:SetVAlign(ANCHOR_TOP)
        part_content:SetHAlign(ANCHOR_LEFT)
        part_content:EnableWordWrap(true)
        
        
        local part_x, part_y = 160, -70
        part_time:SetPosition(part_x, part_y)
        part_line:SetPosition(part_x, part_y-20)
        part_content:SetPosition(self.width_bg/1.45, -320)
        table.insert(part_list, _part)
    end    
    local scroll = self.right:AddChild(ScrollableList(part_list, self.width_bg*1.2, self.height_bg, self.height_bg*0.7, 5, nil, nil, 0, false, nil, nil, nil, nil, "BLACK"))
    -- scroll:SetPosition(self.leftpos_content,  0)
end

function TheWindow:ShowInfo()
    if type(self.modinfo.description) ~= "string" then return end
    self.right:KillAllChildren()
    local text = self.right:AddChild(Text(HEADERFONT, 35, "", UICOLOURS.BLACK))
    text:SetVAlign(ANCHOR_TOP)
    text:SetHAlign(ANCHOR_LEFT)
    text:SetRegionSize(self.width_content, self.height_content)
    text:EnableWordWrap(true)
    text:SetString(self.modinfo.description)
end

function TheWindow:GameRecord()
    local text = self.right:AddChild(Text(HEADERFONT, 40, "", UICOLOURS.BLACK))
    text:SetVAlign(ANCHOR_TOP)
    text:SetHAlign(ANCHOR_LEFT)
    text:SetRegionSize(self.width_content, self.height_content)
    text:EnableWordWrap(true)
    text:SetString([[
        该功能开发中，以后这里会这样显示：

        该怎么形容你的饥荒呢：（冒险家/建家大佬/睡大觉/好朋友/吃吃吃）
        我们第一次相遇 XX年XX月XX日，一转眼XX天了
        今年你一共打了 XX 个BOSS，最喜欢打的是 (龙蝇/巨鹿/蜂后...)
        你大部分时间都在玩 （温蒂/大力士/老奶奶...）
        你开档每次都有这个模组：XXX
        永恒领域陪伴你最久的朋友是 XX

        XX月XX日，你睡的很晚，XX:XX还在用XX 做 XX~
        XX月XX日，是你重生次数最多的一天，XX 很难打赢吧~
        你吃了XX个XX，这道菜一定很可口吧~
        春天，你装备XX，做XXXXX
        夏天，你身处XX，和XXXXX
        秋天，你收集XX，用XXX
        冬天，你努力XX，将XXX

        看看你的成就：
        （这里会展示图片，显示一些其他玩家很难做到的事，比如生存多少天，打了多少次天体）

        你的年度饥荒标签：（冒险家/建家大佬/睡大觉/好朋友/吃吃吃）
        你的年度食物/角色：（）

        感谢致词。。。
]])
end

function TheWindow:Game()
    local text = self.right:AddChild(Text(HEADERFONT, 40, "", UICOLOURS.BLACK))
    text:SetVAlign(ANCHOR_TOP)
    text:SetHAlign(ANCHOR_LEFT)
    text:SetRegionSize(self.width_content, self.height_content)
    text:EnableWordWrap(true)
    text:SetString([[
        还没写，下次一定！
]])
end

function TheWindow:DesktopSaver()
    local par = self.parent and self.parent.parent
    local elements = {"lIcon", "connect_menu","onlinestatus","menu_root","logo","sidebar","motd_panel","submenu","build_number","kit_puppet",}
    
    if type(par) == "table" then
        local br = par.banner_root and par.banner_root.children
        if not self.show_desktop then
            for _, element_name in pairs(elements)do
                if par[element_name] and par[element_name].Hide then
                    par[element_name]:Hide()
                end
            end
            if type(br) == "table" then
                for k,v in pairs(br)do
                    if type(k) == "table" and k.name ~= "UIAnim" and k.Hide then
                        k:Hide()
                    end
                end
            end
        else
            for _, element_name in pairs(elements)do
                if par[element_name] and par[element_name].Show then
                    par[element_name]:Show()
                end
            end
            if type(br) == "table" then
                for k,v in pairs(br)do
                    if type(k) == "table" and k.name ~= "UIAnim" and k.Show then
                        k:Show()
                    end
                end
            end
        end
        self.show_desktop = not self.show_desktop
    end

    
    local text = self.right:AddChild(Text(HEADERFONT, 40, "", UICOLOURS.BLACK))
    text:SetVAlign(ANCHOR_TOP)
    text:SetHAlign(ANCHOR_LEFT)
    text:SetRegionSize(self.width_content, self.height_content)
    text:EnableWordWrap(true)
    text:SetString('屏保状态：'..(self.show_desktop and '开启' or '关闭').."\n\n"..
    [[
        屏保模式就是为了方便截图的，看看科雷做的这个主页动画。
        屏保开启时只能通过设定好的面板按键（默认F2）开启或关闭功能面板。
        

        
        试着按下你设置的按键吧！
]])
end


return TheWindow